<template>
  <div class="" style="height: 100%;">
    <!-- <el-select clearable v-model="values" value-key="id" style="width: 20%; position: absolute; top: 10px; left: 10px; z-index: 10" placeholder="请选择商圈">
      <el-option v-for="item in polygons" :key="item.businessAreaCode" :label="item.name" :value="item.businessAreaCode">
      </el-option>
    </el-select> -->
    <el-button
      style="background-color:#fd804c;color: #fff;position: absolute;top: -30px;left: 35%; z-index:10"
      @click="isShowList"
      >查看</el-button
    >
    <el-select
      v-model="value"
      @change="buss"
      value-key="id"
      style="
       width: 12%;
        position: absolute;
          top: -30px;
        left: 45%;
        z-index: 10;
       
      "
      placeholder="请选择"
    >
      <el-option
        v-for="item in obtainList"
        :key="item.cityCode"
        :label="item.cityName"
        :value="item.cityCode"
      >
      </el-option>
    </el-select>
    <el-input
      v-model="input"
      style="
        width: 12%;
        position: absolute;
        top: -30px;
        left: 60%;
        z-index: 10;
      "
      maxlength="10"
      placeholder="创建商圈名称"
    ></el-input>

    <el-button
      style="background-color:#fd804c;color: #fff;position: absolute;top: -30px; left: 73%; z-index: 10"
      @click="addArea"
      >新增并开始绘制商圈</el-button
    >
    <!-- <el-button
                        style="background-color:#fd804c;color: #fff;"
      style="position: absolute; top: 10px; left: 82%; z-index: 10"
      >重置</el-button
    > -->
    <el-button
      style="background-color:#fd804c;color: #fff;position: absolute; top: -30px;left: 90%; z-index: 10"
      @click="sure"
      >保存</el-button
    >
    <div class="amap-wrapper">
      <!-- <el-amap-search-box
        class="search-box"
        :search-option="searchOption"
        :on-search-result="onSearchResult"
      ></el-amap-search-box>-->

      <el-amap
        class="amap-box"
        ref="map"
        :zoom="zoom"
        :center="center"
        :events="events"
        :mapStyle="mapStyle"
      >
        <el-amap-polygon
          v-for="(polygon, index) in polygons"
          :key="index"
          :vid="index"
          :title="polygon.measure"
          :ref="`polygon_${index}`"
          :path="polygon.path"
          editable="true"
          strokeStyle="dashed"
          strokeColor="#FF0000"
          strokeWeight="2"
          strokeOpacity="0.8"
          fillOpacity="0.3"
          fillColor="#1791fc"
          :events="polygon.events"
        ></el-amap-polygon>
      </el-amap>
    </div>
    <div v-show="isShow">
      <div style="width: 360px; position: absolute; top: 10px; left: 10px">
        <el-card class="box-card" style="">
          <el-button
            style="float: right; padding: 3px 0;color: #fc9e76;"
            type="text"
            @click="isClone"
            >关闭</el-button
          >

          <el-table
            :data="polygons"
            border
            size="mini"
            style="width: 100%; max-height: 350px; overflow: auto"
          >
            <el-table-column align="center" label="名称">
              <template slot-scope="scope">
                <div>{{ scope.row.name }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="面积">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.measure ? scope.row.measure : area }}平方米
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="edit(scope)"
                  v-if="scope.row.path.length > 0"
                  style="color: #fc9e76;"
                  type="text"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  @click="draw(scope.$index)"
                  v-else
                  style="color: #fc9e76;"
                  type="text"
                  size="small"
                  >绘制</el-button
                >
                <el-button
                  @click="del(scope)"
                  style="color: #fc9e76;"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
    <div class="Y-text-align-right Y-avg-1" style="margin-top: 10px">
      <!-- <el-button                   style="background-color:#fd804c;color: #fff;" v-if="isEdit" @click="end">结束编辑</el-button>
      <el-button                   style="background-color:#fd804c;color: #fff;" v-if="isDraw" @click="endDraw">结束绘制</el-button>-->
    </div>
  </div>
</template>
<script>
export default {
  props: {
    path: {
      type: Array,
      default: function() {
        return [];
      }
    },
    name: {
      type: String,
      default: function() {
        return "";
      }
    }
  },
  data() {
    let _this = this;
    return {
      isShow: false,
      lting: false,
      obtainList: [],
      props: ["businessAreaCode"],
      falg: true,
      polygonsTwo: [],
      center: [121.44167, 31.181728], //地图中心点坐标 上海
      zoom: 14, //初始化地图显示层级
      mapStyle: "amap://styles/8b6be8ec497009e17a708205348b899a", //设置地图样式
      // searchOption: {
      //   city: "上海",
      //   citylimit: true,
      // },
      input: "",
      isEdit: false,
      pIdx: 0,
      zoom: 14,
      area: 0,
      cityCode: "",
      cityName: "",
      value: localStorage.getItem("cityCode"),
      values: "",
      events: {
        init: o => {},
        click: e => {
          let { lng, lat } = e.lnglat;
          if (_this.isDraw) {
            let arr = [e.lnglat.lng, e.lnglat.lat];
            _this.polygons[_this.pIdx].path.push(arr);
          }
        }
      },
      polygons: [
        // {
        //   path: [],
        //   events: {
        //     click(e) {
        //       _this.clickEdit(_this, this);
        //     },
        //   },
        // },
      ],
      polygonEditor: null,
      isDraw: false
    };
  },

  watch: {},
  mounted() {
    var that = this;
    this.city();
    this.query();
    this.obtain();
    let _this = this;
    setTimeout(function() {
      this.polygons = [];
      let path = _this.path;
      if (path.length > 0) {
        for (let i = 0; i < path.length; i++) {
          const element = path[i];

          let arr = [];
          if (element.aroundLocations.length > 0) {
            for (let j = 0; j < element.aroundLocations.length; j++) {
              const item = element.aroundLocations[j];
              arr.push([item.lng, item.lat]);
            }
          }
          element.path = arr;
          element.events = {
            click(e) {
              _this.clickEdit(_this, this);
            }
          };
          delete element.aroundLocations;
        }
        _this.polygons = path;
      }
    }, 500);
  },
  methods: {
    isShowList() {
      this.isShow = true;
    },
    isClone() {
      this.isShow = false;
    },
    query() {
      this.$http({
        url: "hsssystemadmin/v1/businessManagement/getCenterCoordinates",
        method: "POST",
        data: {
          cityCode: this.cityCode
            ? this.cityCode
            : localStorage.getItem("cityCode"),
          cityName: this.cityName
            ? this.cityName
            : localStorage.getItem("cityName")
        }
      }).then(res => {
        //console.log(res.data);
        let data = JSON.parse(res.data);

        this.center = data.geocodes[0].location.split(",");
      });
    },
    city() {
      this.$http({
        url:
          "hsssystemadmin/v1/businessManagement/getBusinessCoordinates?cityCode=" +
          (this.cityCode ? this.cityCode : localStorage.getItem("cityCode")),
        method: "get"
      }).then(res => {
        var data = res.data;

        var polygons = [];
        for (var i = 0; i < data.length; i++) {
          var obj = {
            path: [],
            businessAreaCode: "",
            name: "",
            events: {
              click(e) {
                _this.clickEdit(_this, this);
              }
            }
          };
          obj.name = data[i].businessAreaName;
          obj.businessAreaCode = data[i].businessAreaCode;
          obj.measure = data[i].businessArea;
          // obj.path = data[i].businessCoordinates[0].aroundLocations
          var element = data[i].businessCoordinates[0];

          for (var j = 0; j < element.aroundLocations.length; j++) {
            const item = element.aroundLocations[j];
            obj.path.push([item.lng, item.lat]);
          }
          polygons.push(obj);
        }
        this.polygons = polygons;
      });
    },
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      //console.log(pois);
      if (pois.length > 0) {
        let center = pois[0];
        this.lng = center.lng;
        this.lat = center.lat;
        this.address = center.name;
        this.center = [center.lng, center.lat];
        this.markers = [[center.lng, center.lat]];
      }
    },
    // 添加多边形区域
    addArea() {
      if (this.input) {
        if (this.falg == false) {
          this.$message.error("您尚未添加新商圈");
          return;
        }
        this.falg = false;
        let _this = this;
        if (this.isDraw) {
          this.endDraw();
        }

        if (this.isEdit) {
          this.end();
        }

        let obj = {
          path: [],
          measure: "",
          name: this.input,
          businessAreaCode: "",
          events: {
            click(e) {
              _this.clickEdit(_this, this);
            }
          }
        };

        this.polygons.push(obj);
        this.polygonsTwo.push(obj);

        if (this.polygons.length > 0) {
          this.draw(this.polygons.length - 1);
        }
      } else {
        this.$message.error("请先输入商圈名称");
      }
    },

    // 绘制多边形
    draw(idx) {
      if (this.isEdit) {
        this.end();
      }
      this.pIdx = idx;
      this.isDraw = true;
    },
    // 删除多边形区域
    del(idx) {
      //console.log(idx);
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.falg = true;
          this.polygonsTwo.splice(idx.row, 1);
          this.area = 0;
          //console.log(this.polygonsTwo, this.polygons);
          this.$http({
            url:
              "hsssystemadmin/v1/businessManagement/updateBusinessStatus?businessAreaCode=" +
              idx.row.businessAreaCode,
            method: "get"
          }).then(res => {
            const { success, errorMsg } = res;
            if (success == 1) {
              this.polygons.splice(idx.$index, 1);
              this.$message.success("删除成功");
            } else {
              this.$message.error(errorMsg);
            }
          });
        })
        .catch(() => {
          _this.$message.error("已取消");
        });
    },

    clickEdit(vm, polygon) {
      if (vm.isDraw) {
        vm.endDraw();
      }
      if (vm.polygonEditor) {
        vm.end();
      }
      vm.isEdit = true;
      let map = vm.$refs.map.$$getInstance();
      //构造折线编辑对象，并开启折线的编辑状态
      let polygonEditor = new AMap.PolyEditor(map, polygon);
      vm.polygonEditor = polygonEditor;
      polygonEditor.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      polygonEditor.on("end", function(event) {});
    },

    // 编辑多边形区域
    edit(idx) {
      this.lting = true;
      if (this.falg == false) {
        this.$message.error("您的商圈尚未编辑完成");
        return;
      }
      this.falg = false;
      var that = this;

      if (this.isDraw) {
        this.endDraw();
      }
      if (this.polygonEditor) {
        this.end();
      }
      this.isEdit = true;
      let pStr = "polygon_" + idx.$index;
      let vm = this;
      let map = vm.$refs.map.$$getInstance();

      let polygon = vm.$refs["polygon_" + idx.$index][0].$$getInstance();

      // 缩放地图到合适的视野级别
      // map.setFitView([polygon]);
      //构造折线编辑对象，并开启折线的编辑状态
      let polygonEditor = new AMap.PolyEditor(map, polygon);
      vm.polygonEditor = polygonEditor;
      polygonEditor.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      polygonEditor.on("end", function(event) {
        // event.target 即为编辑后的多边形对象,event.target.getPath()得到编辑完成后的点数组
        let pointArr = event.target.getPath();
        vm.polygons[idx.$index].path = pointArr;
        //console.log(pointArr);
        var obj = {
          path: [],
          businessAreaCode: idx.row.businessAreaCode,
          name: idx.row.name,

          events: {
            click(e) {
              _this.clickEdit(_this, this);
            }
          }
        };
        for (var i = 0; i < pointArr.length; i++) {
          const item = pointArr[i];
          //console.log([item.lng, item.lat]);
          obj.path.push([item.lng, item.lat]);
        }
        that.polygonsTwo.push(obj);
        //console.log(that.polygonsTwo);
      });
    },
    // 结束编辑
    end() {
      this.polygonEditor.close();
      this.isEdit = false;
    },
    // 结束绘制
    endDraw() {
      this.isDraw = false;
    },
    // 城市
    obtain() {
      this.$http({
        url: "/hsssystemadmin/v1/businessManagement/getCityList",
        method: "get"
      }).then(res => {
        this.obtainList = res.data;
        //console.log(this.obtainList);
      });
    },
    // 更换
    buss(val) {
      let obj = {};
      obj = this.obtainList.find(item => {
        return item.cityCode === val;
      });
      if (obj != undefined) {
        this.cityName = obj.cityName;
        this.cityCode = obj.cityCode;
        window.localStorage.setItem("cityName", obj.cityName);
        window.localStorage.setItem("cityCode", obj.cityCode);
      } else {
        window.localStorage.setItem("cityName", "上海");
        window.localStorage.setItem("cityCode", "021");
      }

      this.query();
      this.city();
    },
    // 确定 传数据给父组件
    sure() {
      if (this.isDraw) {
        this.endDraw();
      }
      if (this.isEdit) {
        this.end();
      }

      if (this.polygonsTwo.length <= 0) {
        this.$message.error("请您先绘制商圈");

        return;
      }
      for (let i = 0; i < this.polygonsTwo.length; i++) {
        var arr = [];
        const element = this.polygonsTwo[i];
        element.aroundLocations = element.path;
        for (let j = 0; j < element.path.length; j++) {
          const item = element.path[j];
          if (item instanceof Array) {
            arr.push(item);
          } else {
            arr.unshift([item.lng, item.lat]);
          }
        }
      }
      this.area = Math.round(AMap.GeometryUtil.ringArea(arr));
      let lting = this.lting;
      let center = this.center;
      let polygons = this.polygons;
      let area = this.area;
      let polygonsTwo = this.polygonsTwo;
      let cityCode = this.cityCode
        ? this.cityCode
        : localStorage.getItem("cityCode");
      let cityName = this.cityName
        ? this.cityName
        : localStorage.getItem("cityName");
      if (area == 0) {
        this.$message.error("请您先绘制商圈范围");
        return;
      }
      this.$emit(
        "update",
        polygonsTwo,
        center,
        area,
        cityCode,
        cityName,
        lting
      );
      this.polygonsTwo = [];
      this.falg = true;
    }
  }
};
</script>
<style scoped lang="scss">
.search-box {
  position: absolute;
  top: 0;
  left: 0;
}
.amap-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
